package com.leyou.item.service;

import com.leyou.item.mapper.CategoryMapper;
import com.leyou.item.pojo.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 根据parentId查询类目
     *
     * @param pid
     * @return List<Category>
     */
    public List<Category> queryCategoryListByPid(Long pid) {
        Category category = new Category();
        category.setParentId(pid);
        return categoryMapper.select(category);
    }

    /**
     * 保存分类数据
     * @param category
     */
    public Category save(Category category) {
        Category c= categoryMapper.selectByPrimaryKey(category.getParentId());
        if(!c.getIsParent()){
            c.setIsParent(true);
            categoryMapper.updateByPrimaryKeySelective(c);
        }
        categoryMapper.insert(category);
        return category;
    }

    /**
     * 更新分类数据
     * @param category
     */
    public void update(Category category) {
        categoryMapper.updateByPrimaryKeySelective(category);
    }

    /**
     * 删除分类数据
     * @param
     */
    public void delete(Long id) {
        Category category = new Category();
        category.setParentId(id);
        List<Category> categories = categoryMapper.select(category);

        if(CollectionUtils.isEmpty(categories)){
            categoryMapper.deleteByPrimaryKey(id);
        }else {
            for(Category c:categories){
                delete(c.getId());
            }
            delete(id);
        }
    }

    /**
     * 根据brandId查询分类数据
     * @param bid
     * @return
     */
    public List<Category> queryCategoryListByBrandId(Long bid) {
        return categoryMapper.queryCategoryListByBrandId(bid);
    }


    /**
     * 根据id集合，查询分类名称
     * @param ids
     * @return
     */
    public List<String> queryNamesByIds(List<Long> ids) {
        List<Category> categories = categoryMapper.selectByIdList(ids);
        return categories.stream().map(category -> category.getName()).collect(Collectors.toList());
    }

    public List<Category> queryAllByCid3(Long id) {
        Category c3 = this.categoryMapper.selectByPrimaryKey(id);
        Category c2 = this.categoryMapper.selectByPrimaryKey(c3.getParentId());
        Category c1 = this.categoryMapper.selectByPrimaryKey(c2.getParentId());

        return Arrays.asList(c1,c2,c3);
    }
}
